import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
# from fastapi import Request
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

equipment_mmset_router = APIRouter(prefix="/maintain/equipmentMmset", tags=["保养设定管理"],
                                   dependencies=[Depends(oauth2_scheme)])


class EquipmentMaintenanceSearch(PaginationBase):
    # 筛选条件
    fsiteNo: str = Field(..., description="站点编号")
    feuipmentid: Optional[str] = Field("", description="设备ID")
    fmmlevelno: Optional[str] = Field("", description="保养等级编号")
    fmmtypeno: Optional[str] = Field("", description="保养类型编号")


@equipment_mmset_router.get("/list", summary="保养设定查询接口")
def list_mmset(search: EquipmentMaintenanceSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_equipment_mmset where fsite_no= :fsiteNo "
    param["fsiteNo"] = search.fsiteNo
    if search.feuipmentid != "":
        sql = sql + " and feuipmentid = :feuipmentid "
        param["feuipmentid"] = search.feuipmentid
    if search.fmmlevelno != "":
        sql = sql + " and fmmlevelno = :fmmlevelno "
        param["fmmlevelno"] = search.fmmlevelno
    if search.fmmtypeno != "":
        sql = sql + " and fmmtypeno = :fmmtypeno "
        param["fmmtypeno"] = search.fmmtypeno
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fsite_no,feuipmentid,fmmtypeno,fmmday,fmmlevelno,fmmworktime,fmemo,fupddate,foperator"
    sql = sql + " from s_ts_equipment_mmset where fsite_no= :fsiteNo "
    param["fsiteNo"] = search.fsiteNo
    if search.feuipmentid != "":
        sql = sql + " and feuipmentid = :feuipmentid "
        param["feuipmentid"] = search.feuipmentid
    if search.fmmlevelno != "":
        sql = sql + " and fmmlevelno = :fmmlevelno "
        param["fmmlevelno"] = search.fmmlevelno
    if search.fmmtypeno != "":
        sql = sql + " and fmmtypeno = :fmmtypeno "
        param["fmmtypeno"] = search.fmmtypeno
    if search.order == "desc":
        sql = sql + " order by  feuipmentid,feuipmentid desc "
    else:
        sql = sql + " order by  feuipmentid,feuipmentid "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = search.limit
    param["offset"] = search.offset

    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fsiteno'] = data[key][0]
        d1['feuipmentid'] = data[key][1]
        d1['fmmtypeno'] = data[key][2]
        d1['fmmday'] = data[key][3]
        d1['fmmlevelno'] = data[key][4]
        d1['fmmworktime'] = data[key][5]
        d1['fmemo'] = data[key][6]
        d1['fupddate'] = data[key][7]
        d1['foperator'] = data[key][8]
        data_list.append(d1)

    info_dict = {"list": data_list, "limit": search.limit, "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class EquipmentMaintenanceCreate(BaseModel):
    """保养设定新增请求参数"""
    feuipmentid: str = Field(..., description="设备ID")
    fmmlevelno: str = Field(..., description="保养等级编号")
    fmmtypeno: str = Field(..., description="保养类型编号")
    fsiteNo: str = Field(..., description="站点编号")
    foperator: str = Field(..., description="操作人")
    fupddate: str = Field(..., description="更新日期(yyyy-MM-dd HH:mm:ss)")
    fmemo: Optional[str] = Field("", description="备注")
    fmmday: Optional[str] = Field("1", description="保养周期（天）")
    fmmworktime: Optional[str] = Field("1", description="保养工时")


@equipment_mmset_router.post("/create", summary="保养设定新增接口")
def create_mmset(create: EquipmentMaintenanceCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select feuipmentid from s_ts_equipment_mmset "
            sql = sql + " where fsite_no= :fsiteNo and feuipmentid= :feuipmentid and fmmtypeno= :fmmtypeno "
            data = db.execute(text(sql), {
                "fsiteNo": create.fsiteNo,
                "feuipmentid": create.feuipmentid,
                "fmmtypeno": create.fmmtypeno,
            }).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_equipment_mmset(fsite_no,feuipmentid,fmmtypeno,fmmday,fmmlevelno,fmmworktime,fmemo,fupddate,foperator)"
                sql = sql + " values( :fsiteNo , :feuipmentid , :fmmtypeno , :fmmday , :fmmlevelno , :fmmworktime , :fmemo , :fupddate , :foperator );"
                db.execute(text(sql), {
                    "fsiteNo": create.fsiteNo,
                    "feuipmentid": create.feuipmentid,
                    "fmmtypeno": create.fmmtypeno,
                    "fmmday": create.fmmday,
                    "fmmlevelno": create.fmmlevelno,
                    "fmmworktime": create.fmmworktime,
                    "fmemo": create.fmemo,
                    "fupddate": create.fupddate,
                    "foperator": create.foperator,
                })
                # 返回
                d1 = {}
                d1["fsiteNo"] = create.fsiteNo
                d1["feuipmentid"] = create.feuipmentid
                d1["fmmtypeno"] = create.fmmtypeno
                d1["fmmday"] = create.fmmday
                d1["fmmlevelno"] = create.fmmlevelno
                d1["fmmworktime"] = create.fmmworktime
                d1["fmmworktime"] = create.fmmworktime
                d1["fmemo"] = create.fmemo
                d1["fupddate"] = create.fupddate
                d1["foperator"] = create.foperator
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@equipment_mmset_router.post("/update", summary="保养设定修改接口")
def update_mmset(update: EquipmentMaintenanceCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_equipment_mmset"
            sql = sql + " set fmmday= :fmmday ,fmmworktime= :fmmworktime ,fmmlevelno= :fmmlevelno ,fmemo= :fmemo "
            sql = sql + ",fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where fsite_no= :fsiteNo  and feuipmentid= :feuipmentid and fmmtypeno= :fmmtypeno "
            db.execute(text(sql), {
                "fmmday": update.fmmday,
                "fmmworktime": update.fmmworktime,
                "fmmlevelno": update.fmmlevelno,
                "fmemo": update.fmemo,
                "fupddate": update.fupddate,
                "foperator": update.foperator,
                "fsiteNo": update.fsiteNo,
                "feuipmentid": update.feuipmentid,
                "fmmtypeno": update.fmmtypeno,
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


class EquipmentMaintenanceDelete(BaseModel):
    """保养设定删除请求参数"""
    feuipmentid: str = Field(..., description="设备ID")
    fmmtypeno: str = Field(..., description="保养类型编号")
    fsiteNo: str = Field(..., description="站点编号")


@equipment_mmset_router.delete("/delete", summary="保养设定删除接口")
def delete_mmset(delete: EquipmentMaintenanceDelete, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select count(1) from lims.s_tc_mmitem_head where feuipmentid= :feuipmentid "
            data = db.execute(text(sql), {
                "feuipmentid": delete.feuipmentid,
            }).fetchall()

            if data[0][0] > 0:
                return BaseResponse.success(message="该资料在使用，不能删除")
            else:
                sql = "delete from s_ts_equipment_mmset "
                sql = sql + " where fsite_no= :fsiteNo  and feuipmentid= :feuipmentid and fmmtypeno= :fmmtypeno "
                db.execute(text(sql), {
                    "fsiteNo": delete.fsiteNo,
                    "feuipmentid": delete.feuipmentid,
                    "fmmtypeno": delete.fmmtypeno,
                })
                return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
